local BaseData = require("data.base.BaseData")
local MailData = class("UserData", BaseData)
local MailUnitData = require("data.MailUnitData")

function MailData:ctor()
    MailData.super.ctor(self)

    self._signalGetAllMail = G_NetWorkManager:add(MessageIDConst.ID_S2C_GetAllMail, handler(self, self._s2cGetAllMail))
    self._signalReciveMail =
        G_NetWorkManager:add(MessageIDConst.ID_S2C_ReceivetMail, handler(self, self._s2cReceivetMail))
    self._signalGetMail = G_NetWorkManager:add(MessageIDConst.ID_S2C_GetMail, handler(self, self._s2cGetMail))
    self._signalNorifyMail = G_NetWorkManager:add(MessageIDConst.ID_S2C_NorifyMail, handler(self, self._s2cNorifyMail))

    self:_initData()
end

function MailData:reset()
end

function MailData:clear()
    self._signalGetAllMail:remove()
    self._signalGetAllMail = nil
    self._signalReciveMail:remove()
    self._signalReciveMail = nil
    self._signalGetMail:remove()
    self._signalGetMail = nil
    self._signalNorifyMail:remove()
    self._signalNorifyMail = nil
end

function MailData:_initData()
    self._mails = {}
end

function MailData:_setMailUnitData(data)
    local id = data.id
    local unit = self._mails["k_" .. id]
    if not unit then
        unit = MailUnitData.new()
        self._mails["k_" .. id] = unit
    end
    unit:update(data)
end

function MailData:getMailList()
    local result = {}
    for _, unit in pairs(self._mails) do
        table.insert(result, unit)
    end
    return result
end

function MailData:c2sGetAllMail()
    G_NetWorkManager:send(MessageIDConst.ID_C2S_GetAllMail, {})
end

function MailData:c2sReceivetMail(id)
    G_NetWorkManager:send(MessageIDConst.ID_C2S_ReceivetMail, {id = id})
end

function MailData:c2sGetMail()
    G_NetWorkManager:send(MessageIDConst.ID_C2S_GetMail, {})
end

function MailData:_s2cGetAllMail(id, message)
    if message.ret ~= 1 then
        return
    end
    self._mails = {}
    local awards = rawget(message, "awards")
    G_SignalManager:dispatch(SignalConst.EVENT_MAIL_GET_ALL)
end

function MailData:_s2cReceivetMail(id, message)
    if message.ret ~= 1 then
        return
    end
    local id = rawget(message, "id")
    local awards = rawget(message, "awards")
end

function MailData:_s2cGetMail(id, message)
    if message.ret ~= 1 then
        return
    end
    local mails = rawget(message, "mails")
    for i = 1, #mails do
        self:_setMailUnitData(mails[i])
    end
end

function MailData:_s2cNorifyMail(id, message)
    local mail = rawget(message, "mail")
    for i = 1, #mail do
        self:_setMailUnitData(mail[i])
    end
    G_SignalManager:dispatch(SignalConst.EVENT_MAIL_NOTIFY)
end

return MailData
